var express = require('express');
var router = express.Router();
var common = require('../util/common');
var uuid = require('node-uuid');
var UserService = require('../service/UserService');
require('../util/bootloader');

router.post('/regist', function (req, res) {
	let data = req.body;

	if (!data.account || !data.avatarUrl|| !data.nickName || !data.openid || !data.verify_code || !data.type) {
		return res.json(new ERR("参数不全!", 400));
	}

	data.password = common.encryPassword(data.account);
	data.app_sid = 'niyueling';
	data.uuid = uuid.v4();

	(async () => {
		UserService.regist(data, function(err, result) {
			if(err) {
				return res.json(new ERR(err, 400));
			}

			return res.json(new PKG(result));
		});
	})();
});

router.post('/login', function (req, res) {
	let data = req.body;
	data.password = common.encryPassword(data.password);

	if (!data.account || !data.password || !data.app_sid) {
		return res.json(new ERR("参数不全!", 400));
	}

	(async () => {
		UserService.login(data, function(err, result) {
			if(err) {
				return res.json(new ERR(err, 400));
			}

			return res.json(new PKG(result));
		});
	})();
});

module.exports = router;